package com.mjfeed.controller.m;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mjfeed.Principal;
import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Cart;
import com.mjfeed.entity.Member;
import com.mjfeed.service.CartService;
import com.mjfeed.service.MemberService;
import com.mjfeed.util.Md5Util;
import com.mjfeed.util.WebUtils;

/**
 * @description 注册登录
 * @author zhaominglei
 * @date 2014年10月7日
 */
@Controller("mRegisterLoginController")
@RequestMapping("/m")
public class RegisterLoginController extends BaseController {

	@Resource(name="memberService")
	private MemberService memberService;
	@Resource(name="cartService")
	private CartService cartService;
	
	@RequestMapping(value = { "/register" , "/register/get" }, method=RequestMethod.GET)
	public String register(HttpServletRequest request, HttpServletResponse response, Model model){
		String redirectUrl = request.getParameter("redirectUrl");
		request.setAttribute("redirectUrl", redirectUrl);
		return "m/register";
	}
	
	@RequestMapping(value = "/register/save", method=RequestMethod.POST)
	public String registerSave(Member member, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model){
		member.setPassword(Md5Util.encrypt(member.getPassword()));
		member.setIsEnabled(true);
		member.setIsLocked(false);
		member.setLoginFailureCount(0);
		member.setLockedDate(null);
		member.setRegisterIp(super.getRemoteIpAddr(request));
		member.setLoginIp(super.getRemoteIpAddr(request));
		member.setLoginDate(new Date());
		memberService.save(member);
		
		Cart cart = cartService.getCurrent();
		if (cart != null && cart.getMember() == null) {
			cartService.merge(member, cart);
			WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
			WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
		}

		Map<String, Object> attributes = new HashMap<String, Object>();
		Enumeration<?> keys = session.getAttributeNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			attributes.put(key, session.getAttribute(key));
		}
		session.invalidate();
		session = request.getSession();
		for (Entry<String, Object> entry : attributes.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}

		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
		WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername());

		String redirectUrl = request.getParameter("redirectUrl");
		if (StringUtils.isNotBlank(redirectUrl)) {
			return "redirect:"+redirectUrl;
		} else {
			return "redirect:/m/index.html";
		}
	}
	
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	public @ResponseBody Boolean check() {
		return memberService.isAuthenticated();
	}
	
	@RequestMapping(value = { "/login", "/login/get" }, method=RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model){
		String redirectUrl = request.getParameter("redirectUrl");
		request.setAttribute("redirectUrl", redirectUrl);
		return "m/login";
	}
	
	@RequestMapping(value = "/login/sumbit", method=RequestMethod.POST)
	public String sumbit(Member member, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model){
		if (StringUtils.isEmpty(member.getUsername())) {
			request.setAttribute("message", "用户名不能为空");
			return "m/login";
		}
		if (StringUtils.isEmpty(member.getPassword())) {
			request.setAttribute("message", "密码不能为空");
			return "m/login";
		}

		Member pMember = memberService.getMemberByUsername(member.getUsername());
		if (pMember == null) {
			request.setAttribute("message", "用户不存在");
			return "m/login";
		}
		if (!Md5Util.encrypt(member.getPassword()).equals(pMember.getPassword())) {
			request.setAttribute("message", "密码 不正确");
			return "m/login";
		}
		
		pMember.setLoginIp(request.getRemoteAddr());
		pMember.setLoginDate(new Date());
		pMember.setLoginFailureCount(0);
		memberService.update(pMember);
		
		Cart cart = cartService.getCurrent();
		if (cart != null) {
			if (cart.getMember() == null) {
				cartService.merge(pMember, cart);
				WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME);
				WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME);
			}
		}

		Map<String, Object> attributes = new HashMap<String, Object>();
		Enumeration<?> keys = session.getAttributeNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			attributes.put(key, session.getAttribute(key));
		}
		session.invalidate();
		session = request.getSession();
		for (Entry<String, Object> entry : attributes.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}

		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(pMember.getId(), pMember.getUsername()));
		WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, pMember.getUsername());
		
		String redirectUrl = request.getParameter("redirectUrl");
		if (StringUtils.isNotBlank(redirectUrl)) {
			return "redirect:"+redirectUrl;
		} else {
			return "redirect:/m/member/index.shtml";
		}
	}
	
	@RequestMapping(value = { "/logout", "/logout/get" }, method=RequestMethod.GET)
	public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model){
		session.removeAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
		WebUtils.removeCookie(request, response, Member.USERNAME_COOKIE_NAME);
		return "redirect:/m/";
	}
}
